<?php
namespace App\Services;

use App\Models\Tour;
use App\Models\TourSchedule;
use App\Models\TourSettings;
use App\Models\TourTuan;
use App\Models\Traveler;

/**
 *
 * 旅行下单服务
 *
 * @author shengl@maqu.im
 *
 */
class TourCashierService extends BaseService {

    /**
     * 旅行线路个人下单确认
     * @auth shengl 2017年3月25日16:00:46
     * @param $tour_id
     * @param int $schedule_id
     * @return array
     */
    public function getInitSingle($tour_id,$schedule_id=0,$traveller_ids,$user_id){
        //取路线数据
        $tour = Tour::where('if_show',YES)
            ->where('hidden',NO)
            ->with(["tourExtra"=>function($query){
                $query->select('tour_id','options','travel_days');
            }])
            ->select('tour_id','store_id','tour_name','tags','default_image','allow_singlebuy','price_a','adult_child_joinflg')
            ->find($tour_id);

        if(!$tour){
            return $this->failure('未找到该路线');
        }

        if(!$tour->allow_singlebuy){
            return $this->failure('该路线不可以直接下单');
        }

        $tour->default_image = complete_url($tour->default_image);
        $tour->tourExtra->options = json_decode($tour->tourExtra->options);

        $tour->min_price = $tour->price_a;

        //出行前多少天可以购买
        $stopsale_days = TourSettings::where('tour_id',$tour_id)->value('stopsale_days');

        //如果有选择日程，则处理已选中的日程数据和月份
        $weekarray = array( "日","一", "二", "三", "四", "五", "六",);
        $chosedMnoth = local_date('Y-m',gmtime());
        if($schedule_id && $chosedTourSchedule = TourSchedule::where('tour_id',$tour_id)->find($schedule_id)){
            $rest_time = strtotime(local_date_ymd($chosedTourSchedule->open_date))-strtotime(local_date_ymd(gmtime()));
            $rest_date = $rest_time/86400;
            $chosedTourSchedule->can_choose = $rest_date > $stopsale_days ? 1:0;
            $chosedTourSchedule->rest_date = ceil($rest_date);
            $chosedTourSchedule->singlebuy_config = json_decode($chosedTourSchedule->singlebuy_config,true);
            //个人单买不需要合买配置数据
            unset($chosedTourSchedule->groupbuy_config);
            $chosedTourSchedule->stock = $chosedTourSchedule->stock_defined - $chosedTourSchedule->saled_cnt;
            $chosedTourSchedule->open_date_fmt = local_date_ymd($chosedTourSchedule->open_date);
            $chosedTourSchedule->weekday = '星期'.$weekarray[date("w", $chosedTourSchedule->open_date)];
            $chosedMnoth = local_date('Y-m',$chosedTourSchedule->open_date);
        }else{
            $chosedTourSchedule = new \stdClass;
        }

        //如果已经选择了日程，则取该日程的这个月的相关其他日程数据 如果没有选择，则选择当前日期月份的日程数据
        $tour->chosedMmonth = $chosedMnoth;
        $monthFirstTime = strtotime(date('Y-m-d 23:59:59',   strtotime("$chosedMnoth -1 day")));

        $monthLastTime = strtotime(date('Y-m-d 23:59:59',   strtotime("$chosedMnoth +1 month -1 day")));

        $tourSchedule = TourSchedule::where('tour_id',$tour_id)->whereBetween('open_date', [$monthFirstTime, $monthLastTime])->get();

        if(!$tourSchedule){
            $tourSchedule = new \stdClass;
        }else{
            foreach($tourSchedule as $k => $item){
                $rest_time = strtotime(local_date_ymd($item->open_date))-strtotime(local_date_ymd(gmtime()));
                $rest_date = $rest_time/86400;
                $item->can_choose = $rest_date > $stopsale_days ? 1:0;
                $item->rest_date = ceil($rest_date);
                $item->singlebuy_config = json_decode($item->singlebuy_config);
                $item->open_date_fmt = local_date_ymd($item->open_date);
                //个人单买不需要合买配置数据
                unset($item->groupbuy_config);
            }
        }

        //是否有选择出行人
        $travellers =[];

        if($traveller_ids){

//            $ids = explode(',',$traveller_ids);
//            if(count($ids)>0){
//
//                $datas = Traveler::whereIn('traveler_id',$ids)
//                    ->where('user_id',$user_id)
//                    ->get();
//                if($datas){
//                    foreach($datas as $item){
//                        $travellers[]=[
//                            'traveler_id'=>$item->traveler_id,
//                            'traveler_name'=>$item->traveler_name,
//                            'is_child'=>$item->is_child,
//                            'card_type'=>$item->card_type,
//                            'id_card'=>$item->id_card
//                        ];
//                    }
//                }
//            }
            $datas = Traveler::whereIn('traveler_id',$traveller_ids)
                ->where('user_id',$user_id)
                ->get();
            if($datas){
                foreach($datas as $item){
                    $travellers[]=[
                        'traveler_id'=>$item->traveler_id,
                        'traveler_name'=>$item->traveler_name,
                        'is_child'=>$item->is_child,
                        'card_type'=>$item->card_type,
                        'id_card'=>$item->id_card
                    ];
                }
            }
        }

        //返回结果
        $data = new \stdClass;

        $tourScheduleData = new \stdClass;
        foreach($tourSchedule as $item){
            $date = local_date('j',$item->open_date);
            $tourScheduleData->$date = $item;
        }

        // function getTimeWeek($time, $i = 0) {
        //   $weekarray = array("一", "二", "三", "四", "五", "六", "日");
        //   $oneD = 24 * 60 * 60;
        //   return "周" . $weekarray[date("w", $time + $oneD * $i)];
        // }
        // $time=time();


        unset($tour->allow_singlebuy);
        $data->tour = $tour;
        $data->tourSchedule = $tourScheduleData;
        $data->chosedTourSchedule= $chosedTourSchedule;
        $data->travellers = $travellers;

        return $this->success($data);
    }


    /**
     * 旅行线路开团下单确认
     * @auth shengl 2017年3月25日16:00:46
     * @param $tour_id
     * @param int $schedule_id
     * @return array
     */
    public function initCreateTourGroup($tour_id,$schedule_id=0,$traveller_ids,$user_id){

        //取路线数据
        $tour = Tour::where('if_show',YES)
            ->where('hidden',NO)
            ->with('tourImage')
            ->select('tour_id','store_id','tour_name','allow_groupbuy','adult_child_joinflg')
            ->find($tour_id);

        if(!$tour){
            return $this->failure('未找到该路线');
        }

        if(!$tour->allow_groupbuy){
            return $this->failure('该路线不可以团购下单');
        }

        if($tour->tourImage){
            foreach($tour->tourImage as $item){
                $item->image_url = complete_url($item->image_url);
                $item->thumbnail = complete_url($item->thumbnail);
            }
        }

        //出行前多少天可以购买
        $stopsale_days = TourSettings::where('tour_id',$tour_id)->value('stopsale_days');

        //如果有选择日程，则处理已选中的日程数据和月份
        $chosedMnoth = local_date('Y-m',gmtime());

        $chosedTourSchedule =null;

        if($schedule_id){
            $chosedTourSchedule = TourSchedule::where('tour_id',$tour_id)->find($schedule_id);
        } else {
            $chosedTourSchedule =  TourSchedule::where('tour_id',$tour_id)
                ->where('stock','>',0)
                ->where('open_date','>=',gmtime() - $stopsale_days*86400)
                ->orderBy('open_date','asc')
                ->first();
        }

        if($chosedTourSchedule){
            $rest_time = strtotime(local_date_ymd($chosedTourSchedule->open_date))-strtotime(local_date_ymd(gmtime()));
            $rest_date = $rest_time/86400;
            $chosedTourSchedule->can_choose = $rest_date > $stopsale_days ? 1:0;
            $chosedTourSchedule->rest_date = ceil($rest_date);

            $chosedTourSchedule->groupbuy_config = json_decode($chosedTourSchedule->groupbuy_config,true);
            $piao = $chosedTourSchedule->groupbuy_config;
            $chosedTourSchedule->stock = intval(($chosedTourSchedule->stock_defined - $chosedTourSchedule->saled_cnt)/($piao['limit_a'] + $piao['limit_c']));
            if($piao['limit_c']>0){
                $chosedTourSchedule->groupbuy_piao = $piao['limit_a'].'成人+'.$piao['limit_c'].'儿童';
            }else{
                $chosedTourSchedule->groupbuy_piao = $piao['limit_a'].'成人';
            }

            //团购不需要个人单买配置数据
            unset($chosedTourSchedule->singlebuy_config);
            $chosedTourSchedule->open_date_fmt = local_date_ymd($chosedTourSchedule->open_date);
            $chosedMnoth = local_date('Y-m',$chosedTourSchedule->open_date);
        } else {
            //$chosedTourSchedule = new \stdClass;
            return $this->failure('该路线没有可选择的日程');
        }

        //如果已经选择了日程，则取该日程的这个月的相关其他日程数据 如果没有选择，则选择当前日期月份的日程数据
        $tour->chosedMmonth = $chosedMnoth;

//        $monthFirstTime = strtotime($chosedMnoth);
//
//        $monthLastTime = strtotime(date('Y-m-d 23:59:59',   strtotime("$chosedMnoth +1 month -1 day")));
//
//        $tourSchedule = TourSchedule::where('tour_id',$tour_id)->whereBetween('open_date', [$monthFirstTime, $monthLastTime])->get();
//
//        if(!$tourSchedule){
//            $tourSchedule = new \stdClass;
//        }else{
//            foreach($tourSchedule as $k => $item){
//                $rest_time = strtotime(local_date_ymd($item->open_date))-strtotime(local_date_ymd(gmtime()));
//                $rest_date = $rest_time/86400;
//                $item->can_choose = $rest_date > $stopsale_days ? 1:0;
//                $item->rest_date = ceil($rest_date);
//                $item->groupbuy_config = json_decode($item->groupbuy_config);
//                $item->open_date_fmt = local_date_ymd($item->open_date);
//                //团购不需要个人单买配置数据
//                unset($item->singlebuy_config);
//            }
//        }

        //是否有选择出行人
        $travellers =[];

        if($traveller_ids){

            $datas = Traveler::whereIn('traveler_id',$traveller_ids)
                ->where('user_id',$user_id)
                ->get();
            if($datas){
                foreach($datas as $item){
                    $travellers[]=[
                        'traveler_id'=>$item->traveler_id,
                        'traveler_name'=>$item->traveler_name,
                        'is_child'=>$item->is_child,
                        'card_type'=>$item->card_type,
                        'id_card'=>$item->id_card
                    ];
                }
            }
        }

        //返回结果
        $data = new \stdClass;

//        $tourScheduleData = new \stdClass;
//        foreach($tourSchedule as $item){
//            $date = local_date('j',$item->open_date);
//            $tourScheduleData->$date = $item;
//        }
        unset($tour->allow_groupbuy);
        $data->tour = $tour;
        //$data->tourSchedule = $tourScheduleData;
        $data->chosedTourSchedule= $chosedTourSchedule;
        $data->travellers = $travellers;

        return $this->success($data);
    }

    /**
     * 旅行线路参团下单确认
     * @auth shengl 2017年3月25日16:00:46
     * @param $tuan_id
     * @param $user_id
     * @return array
     */
    public function initJoinTourGroup($tuan_id,$user_id,$traveller_ids){
        //取路线数据
        //获取团数据
        $tourTuan = TourTuan::with(['tour'=>function($query){
            $query->select('tour_id','tour_name','short_name','default_image','allow_groupbuy','adult_child_joinflg','tags','price_a','cate_name','to_region_name');
        },'tour.tourExtra'=>function($query){
            $query->select('tour_id','travel_days');
        },'tourTuanData'=>function($query){
            $query->where('state',TUAN_DATA_STATE_SUCCESS)->select('tuan_id','user_id','nickname','portrait');
        }])->where('state','<>',TUAN_STATE_DEFAULT)->select('tuan_id','tour_id','state','slogan','tuanzhang','start_time','end_time','copy_tour_date','copy_peoples','rest_copies','copy_price','tuan_type','copy_config')->find($tuan_id);

        if(!$tourTuan){
            return $this->failure('该路线暂无人员开启团购');
        }
        foreach($tourTuan->tourTuanData as $item){
//            if($user_id == $item->user_id){
//                return $this->failure('您已参加过该次团购,无法继续参团');
//            }
            unset($item->tuan_id,$item->user_id);
            $item->portrait = complete_url($item->portrait);
        }

        //是否有选择出行人
        $travellers =[];

        if($traveller_ids){

            $datas = Traveler::whereIn('traveler_id',$traveller_ids)
                ->where('user_id',$user_id)
                ->get();
            if($datas){
                foreach($datas as $item){
                    $travellers[]=[
                        'traveler_id'=>$item->traveler_id,
                        'traveler_name'=>$item->traveler_name,
                        'is_child'=>$item->is_child,
                        'card_type'=>$item->card_type,
                        'id_card'=>$item->id_card
                    ];
                }
            }
        }

        $tourTuan->tour->min_price = $tourTuan->tour->price_a ;
        $piao =json_decode($tourTuan->copy_config,true);
        $tourTuan->rest_copies = intval($tourTuan->rest_copies/($piao['limit_a'] + $piao['limit_c']));
        $tourTuan->copy_peoples = intval($tourTuan->copy_peoples/($piao['limit_a'] + $piao['limit_c']));
        if($piao['limit_c']>0){
            $tourTuan->groupbuy_piao = $piao['limit_a'].'成人+'.$piao['limit_c'].'儿童';
        }else{
            $tourTuan->groupbuy_piao = $piao['limit_a'].'成人';
        }
        if($tourTuan->end_time <= gmtime()){
            $tourTuan->can_joingroup = 0;
        }else{
            $tourTuan->can_joingroup = 1;
        }
        $tourTuan->start_time_fmt= local_date('Y-m-d H:i',$tourTuan->start_time);
        $tourTuan->end_time_fmt= local_date('Y-m-d H:i',$tourTuan->end_time);
        $tourTuan->copy_tour_date_fmt= local_date_ymd($tourTuan->copy_tour_date);
        $tourTuan->copy_config = json_decode($tourTuan->copy_config);
        $tourTuan->tour->default_image = complete_url($tourTuan->tour->default_image);
        $tourTuan->state_text = TourTuanService::getTuanStateText($tourTuan->state);
        $tourTuan->tuan_type_text = TourTuanService::getTuanTypeText($tourTuan->tuan_type);
        $tourTuan->travellers=$travellers;

        return $this->success($tourTuan);
    }

}
